package com.foodie.servlet;

import com.foodie.entity.Menu;
import com.foodie.entity.User;
import com.foodie.service.MenuService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@WebServlet("/upload")
@MultipartConfig
public class UploadMenuServlet extends HttpServlet {
    MenuService menuService = new MenuService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String introduce = req.getParameter("introduce");
        Part img = req.getPart("img");
        String details = req.getParameter("details");
        String type = req.getParameter("type");

        InputStream is = img.getInputStream();
        String fileName = img.getSubmittedFileName();
        String saveFileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
        FileOutputStream fos = new FileOutputStream("D://" + saveFileName);
        byte[] sc = new byte[1024];
        int len = 0;
        while ((len = is.read(sc)) > 0) {
            fos.write(sc, 0, len);
        }
        fos.flush();
        fos.close();
        is.close();
        //获取操作人信息
        Cookie[] cookies = req.getCookies();
        String token = "";
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("token")) {
                    token = cookies[i].getValue();
                    break;
                }
            }
        }
        ;

        Menu menu = new Menu();
        menu.setMENU_NAME(name);
        menu.setMENU_INTRODUCE(introduce);
        menu.setIMAGE("download?n=" + saveFileName);
        menu.setMENU_DETAILS(details);
        menu.setTOKEN(token);
        menu.setMENU_TYPE(type);
        menu.setVIEW(0);
        menuService.add(menu);
        resp.sendRedirect(req.getContextPath() + "/upload.jsp");

    }

}
